//
//  UIImage+YC.m
//  YCSchool
//
//  Created by yanglinxia on 16/4/26.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "UIImage+YC.h"
#import "GOUtility.h"

@implementation UIImage (YC)

// 返回一张具有边界的图片
+ (instancetype)yc_circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
    // 1.加载原图
    UIImage *oldImage = [UIImage imageNamed:name];
    
    // 2.开启上下文
    CGFloat imageW = oldImage.size.width + 2 * borderWidth;
    CGFloat imageH = oldImage.size.height + 2 * borderWidth;
    CGSize imageSize = CGSizeMake(imageW, imageH);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    
    // 3.取得当前的上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 4.画边框(大圆)
    [borderColor set];
    CGFloat bigRadius = imageW * 0.5; // 大圆半径
    CGFloat centerX = bigRadius; // 圆心
    CGFloat centerY = bigRadius;
    CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx); // 画圆
    
    // 5.小圆
    CGFloat smallRadius = bigRadius - borderWidth;
    CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
    // 裁剪(后面画的东西才会受裁剪的影响)
    CGContextClip(ctx);
    
    // 6.画图
    [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
    
    // 7.取图
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 8.结束上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

// 生成一张可拉伸的图片
+ (instancetype)yc_strechImageWithImageName:(NSString *)imageName
{
    UIImage *oldImage = [UIImage imageNamed:imageName];
    
    CGFloat left = oldImage.size.width / 2;
    CGFloat right = oldImage.size.height / 2;
    
    return [oldImage resizableImageWithCapInsets:UIEdgeInsetsMake(right, left, right, left)];
}

// 生成一张未渲染的图片
+(UIImage *)yc_imageRenderOriginalWithImageNamed:(NSString *)imageName{
    
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return image;
}

// 修改图片大小
+ (instancetype)yc_imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize) newSize
{
    //  newSize.height= image.size.height*(newSize.width/image.size.width);
    newSize.height = newSize.width;
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}

// 圆形图片
- (instancetype)yc_circleImage
{
    UIGraphicsBeginImageContext(self.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctx, rect);
    CGContextClip(ctx);
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

// 生成一张圆形图
+ (instancetype)yc_circleImageNamed:(NSString *)name
{
    return [[self imageNamed:name] yc_circleImage];
}


// 在周边加一个边框为1的透明像素(矩形图片)
- (UIImage *)yc_imageAntialias
{
    CGFloat border = 1.0f;
    //矩形框
    CGRect rect = CGRectMake(border, border, self.size.width - 2 * border, self.size.height - 2 * border);
    
    UIImage *img = nil;
    //开始上下文
    UIGraphicsBeginImageContext(CGSizeMake(rect.size.width,rect.size.height));
    //把图片画到上下文中
    [self drawInRect:CGRectMake(-1, -1, self.size.width, self.size.height)];
    //获取图片
    img = UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();
    
    //开启上下文
    UIGraphicsBeginImageContext(self.size);
    //绘制图片(图片大小比上下文小1x1的边距)
    [img drawInRect:rect];
    //获取图片
    UIImage* antiImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();
    
    return antiImage;
}

+ (UIImage *)yc_imageFromBase64Str:(NSString *)encodedImageStr
{
    NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
    return decodedImage;
}


+ (UIImage *)yc_imageWithColor:(UIColor *)color size:(CGSize)size
{
    if(CGSizeEqualToSize(size, CGSizeZero)) return nil;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context,  (CGRect){CGPointZero, size});
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)yc_imageWithColor:(UIColor *)color size:(CGSize)size radius:(CGFloat)radius
{
    if(CGSizeEqualToSize(size, CGSizeZero)) return nil;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    GOCGContextAddRoundedRect(context,  (CGRect){CGPointZero, size} , radius);
    CGContextClip(context);
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context,  (CGRect){CGPointZero, size});
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//自动处理拍出来的照片方向不对
- (UIImage *)yc_fixOrientationImage
{
    // No-op if the orientation is already correct.
    if (self.imageOrientation == UIImageOrientationUp) {
        return self;
    }
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height, self.size.width), self.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context.
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    
    return img;
}

- (UIImage *)yc_roundImageWithSize:(CGSize)size radius:(CGFloat)radius
{
    @autoreleasepool
    {
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGFloat scale = [UIScreen mainScreen].scale;
        
        size_t width  = size.width * scale;
        size_t height = size.height * scale;
        
        CGSize is = self.size;
        if(is.width > is.height)
        {
            is.width = size.height * is.width / is.height;
            is.height = size.height;
        }
        else
        {
            is.height = size.width * is.height / is.width;
            is.width = size.width;
        }
        CGRect rect;
        rect.size = is;
        rect.origin.x = (size.width - is.width) / 2.0;
        rect.origin.y = (size.height - is.height) / 2.0;
        
        CGContextRef ctx = CGBitmapContextCreate(NULL,
                                                 width,
                                                 height,
                                                 8,
                                                 width * 4,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
        //缩放
        CGContextScaleCTM(ctx, scale, scale);
        GOCGContextAddRoundedRect(ctx,  (CGRect){CGPointZero, size} , radius);
        CGContextClosePath(ctx);
        CGContextClip(ctx);
        CGContextDrawImage(ctx, rect, self.CGImage);
        CGImageRef img = CGBitmapContextCreateImage(ctx);
        UIImage *image = [UIImage imageWithCGImage:img scale:scale orientation:UIImageOrientationUp];
        
        CGImageRelease(img);
        CGContextRelease(ctx);
        
        return image;
    }
}

+ (UIImage *)yc_roundPlaceHolderImageForSize:(CGSize)size
{
    NSString *url = [NSString stringWithFormat:@"http://app.ios.gmall88.com/placeholder.png?width=%lu&height=%lu",(unsigned long)size.width,(unsigned long)size.height];
    
    SDImageCache *cache = [SDImageCache sharedImageCache];
    UIImage *image = [cache imageFromMemoryCacheForKey:url];
    if(image) return image;
    
    @autoreleasepool
    {
        NSString *pkey;
        
        CGFloat w = size.width * 0.3;
        if(w <= 100)
        {
            pkey = @"small_placeholder.png";
        }
        else if(w > 100 && w <= 200)
        {
            pkey = @"middle_placeholder.png";
        }
        else
        {
            pkey = @"big_placeholder.png";
        }
        UIImage *gImage = [UIImage imageNamed:pkey];
        
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGFloat scale = [UIScreen mainScreen].scale;
        
        size_t width  = size.width * scale;
        size_t height = size.height * scale;
        
        CGContextRef ctx = CGBitmapContextCreate(NULL,
                                                 width,
                                                 height,
                                                 8,
                                                 width * 4,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
        CGColorSpaceRelease(colorSpace);
        //缩放
        CGContextScaleCTM(ctx, scale, scale);
        GOCGContextAddRoundedRect(ctx,  (CGRect){CGPointZero, size} , size.width/2.0);
        CGContextClosePath(ctx);
        CGContextClip(ctx);
        CGContextSetFillColorWithColor(ctx, [UIColor yc_colorWithUInt:0xdcdcdc].CGColor);
        CGContextFillRect(ctx, CGRectMake(0, 0, width, height));
        CGContextDrawImage(ctx, CGRectInset(CGRectMake(0, 0, size.width, size.height), (size.width - w)/2.0, (size.height - w)/2.0), gImage.CGImage);;
        
        CGImageRef img = CGBitmapContextCreateImage(ctx);
        image = [UIImage imageWithCGImage:img scale:scale orientation:UIImageOrientationUp];
        
        CGImageRelease(img);
        CGContextRelease(ctx);
        
        [cache storeImage:image forKey:url toDisk:NO];
        
        return image;
    }
}



+ (UIImage *)yc_placeHolderImageForSize:(CGSize)size
{
    if(CGSizeEqualToSize(size,CGSizeZero))
    {
        return nil;
    }
    static NSCache *cache = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cache = [[NSCache alloc] init];
    });
    
    NSString *key = NSStringFromCGSize(size);
    UIImage *image = [cache objectForKey:key];
    if(!image)
    {
        CGRect rect = (CGRect){CGPointZero,size};
        
        NSString *pkey;
        
        CGFloat w = size.width * 0.3;
        if(w <= 100)
        {
            pkey = @"small_placeholder.png";
        }
        else if(w > 100 && w <= 200)
        {
            pkey = @"middle_placeholder.png";
        }
        else
        {
            pkey = @"big_placeholder.png";
        }
        UIImage *gImage = [cache objectForKey:pkey];
        if(!gImage)
        {
            gImage = [UIImage imageNamed:pkey];
            [cache setObject:pkey forKey:gImage];
        }
        
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [UIColor yc_colorWithUInt:0xdcdcdc].CGColor);
        CGContextFillRect(context,  (CGRect){CGPointZero, size});
        
        [gImage drawInRect:CGRectInset(rect, (CGRectGetWidth(rect)-w)/2.0, (CGRectGetHeight(rect)-w)/2.0)];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        if(image)
        {
            [cache setObject:image forKey:key];
        }
    }
    
    return image;
}



@end
